import { constantRoutes } from '@/router'
import { apiRoutes } from './data'
import { list } from '@/api/menu'
import Layout from '@/layout'
import router from '@/router'
import Router from 'vue-router'


const state = {
  routes: [],
  addRoutes: [],
  permissions: [],//按钮权限
}




export function filterAsyncRoutes2(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    // 为菜单
    if (tmp.type === 1) {
      tmp.meta = {
        title: tmp.name,
        icon: tmp.icon
      }
      if (tmp.component == 'Layout') {
        tmp.component = Layout
      } else {
        tmp.component = loadView(tmp.component)
      }
      if (tmp.children) {
        tmp.children = filterAsyncRoutes2(tmp.children)
      }
      res.push(tmp)
    }

  })
  return res
}
// 按钮权限数组
function extractButtonPermissions(routes) {
  // const type2Items = apiRoutes
  const type2Items = routes
    .flatMap(route => route.children || [])
    .flatMap(children => children.children || [])
    .filter(item => item.type === 2);
  type2Items.forEach(el => state.permissions.push(el.permCode))
  return state.permissions;
}




const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes.reverse()
    state.routes = constantRoutes.concat(routes)
  },
  SET_BUTTON: (state, btns) => {
    state.permissions = btns
  }
}





export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}





const actions = {
  async generateRoutes({ commit }, data) {
    // 接口获取树
    const res = await list({ platform: 1 })

    // console.log(filterAsyncRoutes2(res.content), '处理后端路由------')
    // console.log(extractButtonPermissions(res.content), '按钮权限------')
    router.addRoutes(filterAsyncRoutes2(res.content).concat({ path: '*', redirect: '/404', hidden: true, type: 1 }))
    if (data === 'login') {
      // 如果是登录执行 
      let routes = filterAsyncRoutes2(res.content)
      // 跳转菜单树第一个
      if (routes && routes.length) {
        router.push({ path: routes[0].path + '/' + routes[0].children[0].path })
      } else {
        router.push('/dashboard')
      }
    }

    return new Promise(resolve => {
      commit('SET_ROUTES', filterAsyncRoutes2(res.content).concat({ path: '*', redirect: '/404', hidden: true, type: 1 }))
      commit('SET_BUTTON', extractButtonPermissions(res.content))
      resolve(filterAsyncRoutes2(res.content).concat({ path: '*', redirect: '/404', hidden: true, type: 1 }))
    })
  },
  // 重置路由
  async clearRouter({ commit }, data) {
    commit('SET_BUTTON',[])
    commit('SET_ROUTES',[])
    const newRouter = new Router({
      routes: constantRoutes // 只保留初始路由
    })
    router.matcher = newRouter.matcher // 替换路由匹配器
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
